package com.jp.knowledge.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.DisplayUtil;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.daily_knowledge.DailyKnowledgePackageAdapter;
import com.jp.knowledge.command.Command;
import com.jp.knowledge.command.CommandInvoker;
import com.jp.knowledge.command.CommandReceiver;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.DailyKnowledgePackageModel;
import com.jp.knowledge.model.FoundBanner;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.util.ResultSubscriber;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/25.
 */

public class DailyKnowledgeDetailListFragment extends Fragment implements ResultSubscriber.OnResultListener, CanRefreshLayout.OnRefreshListener {

	private static final int GET_BANNER_CODE = 0x01;
	private static final int GET_LIST_CODE = 0x02;

	private Context mContext;
	private View contentView;
	@ViewInject(R.id.refresh)
	private CanRefreshLayout refreshLayout;
	@ViewInject(R.id.banner_view)
	private Banner bannerView;
	@ViewInject(R.id.permissionView)
	private LinearLayout remindView;
	@ViewInject(R.id.remind_img)
	private ImageView remindImg;
	@ViewInject(R.id.remind_text)
	private TextView remindText;
	@ViewInject(R.id.remind_btn)
	private TextView remindBtn;
	@ViewInject(R.id.content_rv)
	private RecyclerView contentRv;

	private Calendar calendar;
	private String navType;
	private DateFormat dateFormat;
	private int page;
	private List<com.jp.knowledge.model.Banner> banners;
	private List<DailyKnowledgePackageModel> listDatas;
	private DailyKnowledgePackageAdapter adapter;
	private String dataCachePath;
	private String bannerCachePath;
	private FileCacheManager cacheManager;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(contentView == null){
			mContext = getContext();
			contentView = View.inflate(mContext, R.layout.fragment_knowledge_detail_list, null);
			x.view().inject(this, contentView);
			refreshLayout.setLoadMoreEnabled(false);
			refreshLayout.setOnRefreshListener(this);
			initData();
			initBanner();
			initRecyclerView();
			updateData();
		}
		return contentView;
	}

	private void initData(){
		page = 1;
		banners = new ArrayList<>();
		listDatas = new ArrayList<>();
		cacheManager = new FileCacheManager();
		dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
		adapter = new DailyKnowledgePackageAdapter(mContext, listDatas);
	}

	private void initBanner(){
		bannerView.getLayoutParams().height = (int) (DensityUtil.getScreenWidth() * 302f / 922f + 0.5f);
		bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
		bannerView.setIndicatorGravity(BannerConfig.CENTER);
		bannerView.setImageLoader(new ImageLoader(){
			@Override
			public void displayImage(Context context, Object path, ImageView imageView) {
				String imagePath = ((com.jp.knowledge.model.Banner)path).getSrc();
				Glide.with(mContext).load(imagePath).error(R.mipmap.morentutouxiang).into(imageView);
			}
		});
		bannerView.setOnBannerListener(new OnBannerListener() {
			@Override
			public void OnBannerClick(int position) {
				com.jp.knowledge.model.Banner banner = banners.get(position);
				CommandReceiver receiver = new CommandReceiver.Builder(mContext)
						.withCompanyId(banner.getCommpanyId())
						.withRecordId(banner.getRecordId()).build();
				Command command = Command.create(banner.getCommand(), receiver);
				CommandInvoker.executeCommand(command);
			}
		});
	}

	private void initRecyclerView(){
		contentRv.setHasFixedSize(true);
		contentRv.setLayoutManager(new LinearLayoutManager(mContext){
			@Override
			public boolean canScrollVertically() {
				return false;
			}
		});
		contentRv.setAdapter(adapter);
	}

	private void setRemindView(){
		if(contentView == null)
			return;
		if(calendar == null || navType == null)
			refreshLayout.setVisibility(View.GONE);
		else
			refreshLayout.setVisibility(View.VISIBLE);
		if(refreshLayout.getVisibility() == View.GONE
				|| (refreshLayout.getVisibility() == View.VISIBLE && adapter.getItemCount() == 0)){
			remindView.setVisibility(View.VISIBLE);
			remindText.setText("暂无数据~");
			remindBtn.setVisibility(View.GONE);
		} else{
			remindView.setVisibility(View.GONE);
		}
	}

	public void updateData(){
		if(contentView == null || calendar == null || navType == null)
			return;
		setRemindView();
		dataCachePath = mContext.getCacheDir().getPath()
				+ "/daily_knowledge_package_list_"
				+ navType + "_"
				+ dateFormat.format(this.calendar.getTime()) + ".dat";
		bannerCachePath = mContext.getCacheDir().getPath()
				+ "/daily_knowledge_banner_"
				+ navType + "_"
				+ dateFormat.format(this.calendar.getTime()) + ".dat";
		readBannerCache();
		readListData();
	}

	public void updateData(Calendar calendar){
		if(calendar == null || isSameDay(this.calendar, calendar))
			return;
		this.calendar = calendar;
		if(contentView != null) {
			bannerView.setVisibility(View.GONE);
			listDatas.clear();
			adapter.updateAdapter(listDatas);
		}
		updateData();
	}

	public void updateData(String navType){
		if(navType == null || navType.equals(this.navType))
			return;
		this.navType = navType;
		updateData();
	}

	public void updateData(Calendar calendar, String navType){
		if(calendar == null || isSameDay(this.calendar, calendar)
				|| navType == null || navType.equals(this.navType))
			return;
		this.calendar = calendar;
		this.navType = navType;
		if(contentView != null) {
			bannerView.setVisibility(View.GONE);
			listDatas.clear();
			adapter.updateAdapter(listDatas);
		}
		updateData();
	}

	private boolean isSameDay(Calendar calendar1, Calendar calendar2){
		if(calendar1 == null || calendar2 == null
				|| calendar1.get(Calendar.YEAR) != calendar2.get(Calendar.YEAR)
				|| calendar1.get(Calendar.MONTH) != calendar2.get(Calendar.MONTH)
				|| calendar1.get(Calendar.DAY_OF_MONTH) != calendar2.get(Calendar.DAY_OF_MONTH))
			return false;
		return true;
	}

	private void setBannerData(FoundBanner data){
		banners.clear();
		if(data != null && data.getBanner() != null && data.getBanner().size() > 0){
			banners.addAll(data.getBanner());
			bannerView.update(banners);
			bannerView.setVisibility(View.VISIBLE);
		} else{
			bannerView.setVisibility(View.GONE);
		}
	}

	private void getBannerData(){
		JsonObject param = new JsonObject();
		param.addProperty("action", 4);
		param.addProperty("navType", navType);
		param.addProperty("time", dateFormat.format(calendar.getTime()));
		HttpHelper.getInstance(mContext).discoverData(param, GET_BANNER_CODE, this);
	}

	private void getListData(int page){
		JsonObject param = new JsonObject();
		param.addProperty("time", dateFormat.format(calendar.getTime()));
		param.addProperty("navType", navType);
		param.addProperty("page", page);
		HttpHelper.getInstance(mContext).knowledgePackageIndex(param, GET_LIST_CODE, this);
	}

	@Override
	public void onRefresh() {
//		getBannerData();
		getListData(page);
	}

	@Override
	public void onStart(int requestType) {}
	@Override
	public void onCompleted(int requestType) {
		if(requestType == GET_LIST_CODE){
			refreshLayout.refreshComplete();
			refreshLayout.loadMoreComplete();
		}
	}
	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
	}
	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			ToasUtil.toast(mContext, data.getMessage());
		} else if(requestType == GET_BANNER_CODE){
			FoundBanner foundBanner = data.getEntity(FoundBanner.class);
			setBannerData(foundBanner);
			saveCache(foundBanner, bannerCachePath);
		} else if(requestType == GET_LIST_CODE){
			if(page == 1)
				listDatas.clear();
			List<DailyKnowledgePackageModel> datas = data.getList(DailyKnowledgePackageModel.class);
			if(datas != null && datas.size() > 0)
				listDatas.addAll(datas);
			adapter.updateAdapter(listDatas);
			setRemindView();
			saveCache(listDatas, dataCachePath);
		}
	}

	private void readBannerCache(){
		Observable.create(new Observable.OnSubscribe<FoundBanner>() {
			@Override
			public void call(Subscriber<? super FoundBanner> subscriber) {
				FoundBanner appData = (FoundBanner) cacheManager.readObject(bannerCachePath);
				subscriber.onNext(appData);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<FoundBanner>() {
			@Override
			public void onCompleted() {
				getBannerData();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(FoundBanner data) {
				setBannerData(data);
			}
		});
	}

	private void readListData(){
		Observable.create(new Observable.OnSubscribe<List<DailyKnowledgePackageModel>>() {
			@Override
			public void call(Subscriber<? super List<DailyKnowledgePackageModel>> subscriber) {
				List<DailyKnowledgePackageModel> appData = (List<DailyKnowledgePackageModel>) cacheManager.readObject(dataCachePath);
				subscriber.onNext(appData);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<List<DailyKnowledgePackageModel>>() {
			@Override
			public void onCompleted() {
				if(adapter.getItemCount() > 0)
					onRefresh();
				else
					refreshLayout.autoRefresh();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(List<DailyKnowledgePackageModel> data) {
				listDatas.clear();
				if(data != null && data.size() > 0)
					listDatas.addAll(data);
				adapter.updateAdapter(listDatas);
				setRemindView();
			}
		});
	}

	private void saveCache(final Object data, final String path){
		if(path == null)
			return;
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(data, path);
			}
		}).start();
	}
}
